package com.ruoyi.common.utils.baidu;

import com.baidu.aip.face.AipFace;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;

@Component
@Slf4j
public class BaiduAiUtils {

    @Value("${baidu.face.appId}")
    private String APP_ID;
    @Value("${baidu.face.apiKey}")
    private String API_KEY;
    @Value("${baidu.face.secretKey}")
    private String SECRET_KEY;
    @Value("${baidu.face.imageType}")
    private String IMAGE_TYPE;
    @Value("${baidu.face.groupId}")
    private String groupId;

    private AipFace client;

    // 使用 HashMap<String, Object>
    private HashMap<String, Object> options = new HashMap<>();

    public BaiduAiUtils() {
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
    }

    @PostConstruct
    public void init() {
        client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
    }

    public Boolean faceRegister(String userId, String image) {
        // 转换 options 为 HashMap<String, String>
        HashMap<String, String> stringOptions = convertToMapString(options);
        JSONObject res = client.addUser(image, IMAGE_TYPE, groupId, userId, stringOptions);
        log.info("addUser result ：{}", res);
        Integer errorCode = res.getInt("error_code");
        return errorCode == 0;
    }

    public Boolean faceUpdate(String userId, String image) {
        // 转换 options 为 HashMap<String, String>
        HashMap<String, String> stringOptions = convertToMapString(options);
        JSONObject res = client.updateUser(image, IMAGE_TYPE, groupId, userId, stringOptions);
        log.info("updateUser result ：{}", res);
        Integer errorCode = res.getInt("error_code");
        return errorCode == 0;
    }

    public Boolean faceCheck(String image) {
        JSONObject res = client.detect(image, IMAGE_TYPE, options);
        log.info("detect result ：{}", res);
        if (res.has("error_code") && res.getInt("error_code") == 0) {
            JSONObject resultObject = res.getJSONObject("result");
            Integer faceNum = resultObject.getInt("face_num");
            return faceNum == 1;
        } else {
            return false;
        }
    }

    public String faceSearch(String image) {
        JSONObject res = client.search(image, IMAGE_TYPE, groupId, options);
        log.info("search result ：{}", res);
        if (res.has("error_code") && res.getInt("error_code") == 0) {
            JSONObject result = res.getJSONObject("result");
            JSONArray userList = result.getJSONArray("user_list");
            if (userList.length() > 0) {
                JSONObject user = userList.getJSONObject(0);
                double score = user.getDouble("score");
                if (score > 80) {
                    return user.getString("user_id");
                }
            }
        }
        return null;
    }

    // 辅助方法：将 HashMap<String, Object> 转换为 HashMap<String, String>
    private HashMap<String, String> convertToMapString(HashMap<String, Object> objectMap) {
        HashMap<String, String> stringMap = new HashMap<>();
        for (HashMap.Entry<String, Object> entry : objectMap.entrySet()) {
            stringMap.put(entry.getKey(), entry.getValue().toString());
        }
        return stringMap;
    }
}